const dayjs = require("dayjs");
const ossClient = require("../oss/index");
const path = require("path");
const multiparty = require("multiparty");
// 自定义请求头
const headers = {
  // 指定Object的存储类型。
  "x-oss-storage-class": "Standard",
  // 指定Object的访问权限。
  "x-oss-object-acl": "private",
  // 通过文件URL访问文件时，指定以附件形式下载文件，下载后的文件名称定义为example.txt。
  "Content-Disposition": 'attachment; filename="example.txt"',
  // 设置Object的标签，可同时设置多个标签。
  "x-oss-tagging": "Tag1=1&Tag2=2",
  // 指定PutObject操作时是否覆盖同名目标Object。此处设置为true，表示禁止覆盖同名Object。
  "x-oss-forbid-overwrite": "true",
};
// 获取图片列表
exports.getImagesList = (req, res, next) => {
  const title = "获取图片列表";
  res.render("images", { title, title });
};
// 上传图片到oss上面
exports.uploadImage = async (req, res, next) => {
  try {
    const form = new multiparty.Form();
    const { id, team_id } = req.user;
    console.log(id, team_id);
    const sql =
      "SELECT COUNT(*) FROM  fa_images WHERE user_id =? and team_id=?";
    const [result] = await global.query(sql, [id, team_id]);
    if (result["COUNT(*)"] > 0) {
      return res.cc("已上传过图片,请勿重复上传");
    }
    // 上传图片需要保存在一个目录下面，目录必须存在
    // form.uploadDir = "./public/upload";
    form.parse(req, async (err, fields, files) => {
      if (err) {
        return res.cc(err.message);
      }
      // const fileName = files.image[0].originalFilename;
      const fileUrl = files.image[0].path;
      const fileUrlArr = files.image[0].path.split("/");
      const fileName = fileUrlArr.pop();
      const result = await ossClient.put(
        "dev/" + fileName + "",
        path.normalize(fileUrl),
        { headers }
      );
      const url = result.url;
      const description = fields.description;
      const type = fields.type;
      const upload_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      // 将图片URL存入数据库
      const sql =
        "INSERT INTO fa_images (url,name,description,user_id,team_id,type,upload_time) VALUES (?,?,?,?,?,?,?)";
      global
        .query(sql, [
          url,
          fileName,
          description,
          id,
          team_id,
          type,
          upload_time,
        ])
        .then((sqlRes) => {
          if (sqlRes.affectedRows !== 1) {
            return res.cc("上传失败");
          }
          res.cc("上传成功", 200);
        });
    });
  } catch (error) {
    res.cc(error);
  }
};
// 点赞处理模块
exports.likes = async (req, res, next) => {
  const { user_id, team_id, img_id } = req.body;
  const upload_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  try {
    // 查询数据库是否有该图片 0没有 >0 存在
    const sql =
      "SELECT COUNT(*) FROM  fa_images WHERE user_id =? and team_id=? and id=?";
    const [result] = await global.query(sql, [user_id, team_id, img_id]);
    const count = JSON.parse(JSON.stringify(result));
    if (count[0]["COUNT(*)"] == 0) {
      return res.cc("图片不存在，请上传图片！");
    }
    // 查询点赞数量 0 没点赞 >0 已点赞
    const [selectRes] = await global.query(
      "SELECT likes FROM  fa_images WHERE user_id =? and team_id=? and id=?",
      [user_id, team_id, img_id]
    );
    console.log("selectRes---", selectRes);
    // 已经点过赞
    if (selectRes.likes > 0) {
      return res.cc("已成功点赞");
    }
    await global.query(
      "UPDATE fa_images SET likes = likes + 1 ,upload_time= ? WHERE id = ? and user_id = ? ",
      [upload_time, img_id, user_id]
    );
    res.cc("点赞成功", 200);
  } catch (error) {
    console.error(error);
    global.logger.error({
      status: 500,
      message: "点赞失败",
    });
    res.cc("点赞失败");
  }
};
// 评论处理模块
exports.comment = async (req, res, next) => {
  const { img_id, content, user_id, team_id } = req.body;
  const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // console.log("res---", img_id, user_id, content);
  try {
    await global.query(
      "INSERT INTO fa_comment (img_id,status, user_id,team_id, content,create_time) VALUES (?,?,?,?,?,?)",
      [img_id, "1", user_id, team_id, content, create_time]
    );
    global.logger.info({
      status: 200,
      message: "评论成功",
    });
    res.cc("评论成功", 200);
  } catch (error) {
    console.error(error);
    global.logger.error({
      status: 500,
      message: "评论失败",
    });
    return res.cc("评论失败");
  }
};
// test
exports.test = (req, res, next) => {
  global.logger.info({
    status: 200,
    message: "测试成功",
  });
  res.send("测试成功", 200);
};
// 图片方法
exports.getImages = async (req, res, next) => {
  try {
    const form = new multiparty.Form();
    // const { id, team_id } = req.user;
    // console.log(id, team_id);

    // 上传图片需要保存在一个目录下面，目录必须存在
    form.parse(req, async (err, fields, files) => {
      if (err) {
        return res.cc(err.message);
      }
      const employee_no = fields.employee_no;
      const selectSql =
        "SELECT * FROM  kp_images WHERE employee_no = ? ";
      const results = await global.query(selectSql, [employee_no]);
      if (results.length > 0) {
        return  res.cc(results[0], 0);
      }
      res.cc({body: null}, -1);
    });
  } catch (error) {
    res.cc(error);
  }
};
// 图片方法
exports.uploadImages = async (req, res, next) => {
  try {
    const form = new multiparty.Form();
    // const { id, team_id } = req.user;
    // console.log(id, team_id);

    // 上传图片需要保存在一个目录下面，目录必须存在
    form.parse(req, async (err, fields, files) => {
      if (err) {
        return res.cc(err.message);
      }
      console.log("fields", fields)
      const employee_no = fields.employee_no[0];
      const selectSql =
        "SELECT COUNT(*) FROM  kp_images WHERE employee_no = ? ";
      const [results] = await global.query(selectSql, [employee_no]);
      if (results["COUNT(*)"] > 0) {
        return res.cc("已上传过图片,请勿重复上传");
      }
      const img_url = fields.image[0];
      const user_name = fields.user_name[0];
      const group_name = fields.group_name[0];
      const create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      // 将图片URL存入数据库
      const sql =
        "INSERT INTO kp_images (employee_no,user_name,group_name,img_url,create_time) VALUES (?,?,?,?,?)";
      global
        .query(sql, [employee_no, user_name, group_name, img_url, create_time])
        .then((sqlRes) => {
          console.log("sqlRes---", sqlRes);
          if (sqlRes.affectedRows !== 1) {
            return res.cc("上传失败");
          }
          res.cc("上传成功", 200);
        });
    });
  } catch (error) {
    res.cc(error);
  }
};
